package system_unlock_dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type SystemUnlock struct {
	RoleId     int64                               `gorm:"column:role_id;primary"`
	UnlockArr  []byte                               `gorm:"column:unlock_arr"`
	Counter datatypes.JSONType[map[int32]int32] `gorm:"column:counter"`
}

func (SystemUnlock) TableName() string {
	return "system_unlock"
}

var (
	all_system_unlock_field = zutils.GetGormFields(SystemUnlock{})
)

func GetSystemUnlockByKey(roleId int64) *SystemUnlock {
	db := mysql.GetServerDBConnection()
	var systemUnlock SystemUnlock
	if err := db.Select(all_system_unlock_field).Where("role_id=?", roleId).First(&systemUnlock).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetSystemUnlockByKey ERR!!! role_id: %d, err: %v", roleId, err)
		}
		return nil
	}
	return &systemUnlock
}

func NewOrUpdateSystemUnlock(systemUnlock *SystemUnlock) {
	if systemUnlock == nil || len(systemUnlock.UnlockArr) <= 0 {
		return
	}

	db := mysql.GetServerDBConnection()
	if err := db.Clauses(clause.OnConflict{
		Columns: []clause.Column{{Name: "role_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"unlock_arr"}),
	}).Create(systemUnlock).Error; err != nil {
		zlog.Errorf("create or update SystemUnlock %v data failed: %v", systemUnlock, err)
	}
}
